package com.xmut.bs.handaccount.util;

import android.content.Context;
import android.content.SharedPreferences;

public class SharePreferenceManager {

    private static SharedPreferences sp;

    private static SharePreferenceManager instance;

    private static Context mContext;

    public static void init(Context context, String name) {
        sp = context.getSharedPreferences(name, Context.MODE_PRIVATE);
        mContext = context;
    }

    // 单例模式中获取唯一的MyApplication实例
    public static SharePreferenceManager getInstance() {
        if (null == instance) {
            // 同步处理避免同时生成多个实例
            synchronized (mContext.getApplicationContext()) {
                if (null == instance) {
                    instance = new SharePreferenceManager();
                }
            }
        }
        return instance;
    }

    private void setSp(String key, String value) {
        if (null != sp) {
            sp.edit().putString(key, value).apply();
        }
    }

    private String getSp(String key){
        if (null != sp) {
            return sp.getString(key, "");
        }
        return "";
    }

    private final String AUTO_LOGIN = "is_auto_login";

    public void setIsAutoLogin(boolean cityCode) {
        sp.edit().putBoolean(AUTO_LOGIN, cityCode).apply();
    }

    public boolean isAutoLogin() {
        return null == sp || sp.getBoolean(AUTO_LOGIN, true);
    }

    private final String PACKAGE_NAME = "package_name";

    public void setPackageName(String packageName) {
        setSp(PACKAGE_NAME, packageName);
    }

    public String getPackageName() {
        return getSp(PACKAGE_NAME);
    }

    private final String APP_KEY = "app_key";

    public void setAppKey(String appKey) {
        setSp(APP_KEY, appKey);
    }

    public String getAppKey() {
        return getSp(APP_KEY);
    }

    private final String APP_ID = "app_id";

    public void setAppId(String appId) {
        setSp(APP_ID, appId);
    }

    public String getAppId() {
        return getSp(APP_ID);
    }

    private final String USER_NAME = "username";

    public void setUserName(String username) {
        setSp(USER_NAME, username);
    }

    public String getUserName() {
        return getSp(USER_NAME);
    }

}
